#include<iostream>
#include<unistd.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include<cstring>
using namespace std;


void Writer(int wfd)
{
    string s = "hello i am child";
    pid_t id = getpid();
    int number = 0;
    
    char buffer[1024];
    while(1)
    {
        buffer[0] = 0;
        snprintf(buffer, sizeof(buffer), "%s-%d-%d\n", s.c_str(), id, number++);
        cout << buffer << endl;
        //sleep(1);

        write(wfd, buffer, strlen(buffer));
        sleep(1);
    }
}

void Reader(int rfd)
{
    char buffer[1024];
    while(1)
    {
        buffer[0] = 0;
        ssize_t n = read(rfd, buffer, sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = 0;
            cout << "father get a message:[" << getpid() << "]# " << buffer << endl; 
        }
        sleep(1);
    }
}

int main()
{
    int pipefd[2] = {0};
    int fd = pipe(pipefd);
    if(fd < 0) return 1;

    //cout << "pipefd[0]: " << pipefd[0] << "; pipefd[1]: " << pipefd[1] << endl;

    pid_t id = fork();
    if(id < 0) 
        return 2;
    if(id == 0)
    {
        //child; write;
        close(pipefd[0]);

        //write todo;
        Writer(pipefd[1]);

        close(pipefd[1]);
        exit(0);
    }
    //father read;
    close(pipefd[1]);

    Reader(pipefd[0]);

    pid_t rid = waitpid(id, nullptr, 0);
    if(rid < 0)
        return 3;
    close(pipefd[0]);
    return 0;
}